package com.example.cpl.myapplication;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

public class View3 extends AppCompatActivity {
    private Button but_sure, but_clear;
    private EditText et_sg, et_tz;
    private TextView tv_data;
    private int t;
    private String check_sg,check_tz;
//    private SharedPreferences msharedPreferences;
     String filename1 = "MySharedString_View3_1",filename2 = "MySharedString_View3_2",filename3 = "MySharedString_View3_3";
//    ProgressDialog m_pDialog;
    private String change()         //读取对应数据库
    {
        switch(MainActivity.who)
        {
            case 1: return filename1;
            case 2: return filename2;
            case 3: return filename3;
            default:
                return null;
        }

    }
    private void initWidght() {
        tv_data = (TextView) findViewById(R.id.tv_data);
        et_sg = (EditText) findViewById(R.id.et_sg);
        et_tz = (EditText) findViewById(R.id.et_tz);
        but_sure = (Button) findViewById(R.id.but_sure);
        but_clear = (Button) findViewById(R.id.but_clear);
//        tv_data.setMovementMethod(ScrollingMovementMethod.getInstance());
    }
    public String read_SP_Str(String s,String s1) {     //读取数据库的 字符串类型的值
        final SharedPreferences someData = getSharedPreferences(change(), 0);
        return  someData.getString(""+s+"",""+s1+"");
    }
    public int read_SP_Int(String s,int s1) {       //读取数据库的 数值类型的值
        final SharedPreferences someData = getSharedPreferences(change(), 0);
        return  someData.getInt(""+s+"",s1);
    }
    public void  write_SP_Str(String s,String s1) { //写入数据库的 字符串类型的值
        final SharedPreferences someData = getSharedPreferences(change(), 0);
        SharedPreferences.Editor editor = someData.edit();      //让文件 可以编辑
        editor.putString(""+s+"",""+s1+"");
        editor.commit();// 提交修改
    }
    public void  write_SP_Int(String s,int s1) {            //写入数据库的 数值类型的值
        final SharedPreferences someData = getSharedPreferences(change(), 0);
        SharedPreferences.Editor editor = someData.edit();      //让文件 可以编辑
        editor.putInt(""+s+"",s1);
        editor.commit();// 提交修改
    }
    public void clear_SP()
    {
        final SharedPreferences someData = getSharedPreferences(change(), 0);
        SharedPreferences.Editor editor = someData.edit();
        editor.clear();
        editor.commit();

    }
    public String getTime(){
        long time=System.currentTimeMillis();   //long now = android.os.SystemClock.uptimeMillis();
        SimpleDateFormat format=new SimpleDateFormat("MM-dd HH:mm");
        Date d1=new Date(time);
        String t1=format.format(d1);
        Log.d("TAG",t1);
        return t1;
    }
    @SuppressLint("SetTextI18n")
    private void setSP() {
        int i;

        t= read_SP_Int("参数", 0);
//        final SharedPreferences someData = getSharedPreferences(filename, 0);
        tv_data.setText("");
        for (i =1; i <= t ; i++) {              //循环写入历史数据

            String sg_data = read_SP_Str("身高" + "" + i + "", "");
            String tz_data = read_SP_Str("体重" + "" + i + "", "");
            String time_data = read_SP_Str("时间" + "" + i + "", "");
            String bmi_data =read_SP_Str("BMI" + "" + i + "", "");


            tv_data.setText(tv_data.getText() + "记录时间 "+""+time_data+""+"\n"+sg_data + "    " + tz_data +"\n"+bmi_data+"\n\n");
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view3);
        initWidght();

        tv_data.setMovementMethod(ScrollingMovementMethod.getInstance());       //设置text可以滚动
        setSP();//循环写入历史数据

        but_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                clear_SP();
                t=0;
                check_sg=null;
                check_tz=null;
                tv_data.setText("");
                et_sg.setText("");
                et_tz.setText("");


                Toast.makeText(getApplicationContext(), "已清空", Toast.LENGTH_SHORT)
                        .show();//阴影提示框
            }
        });
        but_sure.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onClick(View view){         //保存按钮

                String sg=null;                     //得到记录的数据
                sg=et_sg.getText().toString();
                String tz=null;
                tz=et_tz.getText().toString();

                if(!sg.equals("")&&!tz.equals("")){

                    double intsg = Integer.parseInt(sg);
                    double inttz = Integer.parseInt(tz);
                    if((intsg>10)&&(intsg<300)&&(inttz>10)&&(inttz<300)){       //区间

                        double bmi= inttz/( (intsg/100)*(intsg/100) );

                        DecimalFormat decimalFormat = new DecimalFormat("0.00");//格式化
                        String putbmi=decimalFormat.format(bmi);                        //格式化

                        if (!sg.equals(check_sg)||!tz.equals(check_tz)) {
                            t = t + 1;          //for循环次数
                            String time = getTime();

                            String dat=null;
                            if(bmi<18.5){
                                dat=" 体重过轻！";
                            } else if ((bmi>=18.5)&&(bmi<24)) {
                                dat=" 正常范围";
                            } else if((bmi>=24)&&(bmi<27)) {
                                dat=" 体重过重";
                            } else if(bmi>=27&&bmi<30) {
                                dat=" 轻度肥胖";
                            } else if(bmi>=30&&bmi<35 ) {
                                dat=" 中度肥胖！";
                            } else if(bmi>=35) {
                                dat=" 重度肥胖！";
                            } else {
                                dat=" error！！";
                            }

                            tv_data.setText(tv_data.getText().toString() + "记录时间 " + "" + time + "" + "\n身高为" + "" + et_sg.getText().toString() + "" + "    体重为" + "" + et_tz.getText().toString() + "" +"\nBMI为："+putbmi+dat+ "\n\n");

                            int offset = tv_data.getLineCount() * tv_data.getLineHeight();      //滚动历史数据框
                            if (offset > tv_data.getHeight()) {
                                tv_data.scrollTo(0, offset - tv_data.getHeight());
                            }

                            write_SP_Str("时间" + "" + t + "", time);
                            write_SP_Str("身高" + "" + t + "", "身高为" + et_sg.getText().toString());
                            write_SP_Str("体重" + "" + t + "", "体重为" + et_tz.getText().toString());
                            write_SP_Str("BMI" + "" + t + "", "BMI为：" + putbmi+dat);
                            write_SP_Int("参数", t);

                            check_sg = et_sg.getText().toString();
                            check_tz = et_tz.getText().toString();

                            AlertDialog dlg = new AlertDialog.Builder(View3.this)   //BMI提示框
//                            .setIcon(R.drawable.icon)     //加入提示框图标
                                    .setTitle("BMI")
                                    .setMessage("您的BMI为："+putbmi+dat)
                                    .setPositiveButton("确定", null)

                                    .create();
                            dlg.show();                                                      //BMI提示框

//                            Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT)
//                                    .show();//阴影提示框

//                            Log.d("TAG", "保存的时间= " + "" + time + "" + "  参数= " + "" + t + "");
//                            Log.d("TAG", "保存的身高= " + "" + et_sg.getText().toString() + "" + "  参数= " + "" + t + "");
//                            Log.d("TAG", "保存的体重= " + "" + et_tz.getText().toString() + "" + "  参数= " + "" + t + "");
//                            Log.d("TAG", "SP存储名：时间" + "" + t + "");
//                            Log.d("TAG", "SP存储名：身高" + "" + t + "");
//                            Log.d("TAG", "SP存储名：体重" + "" + t + "");
                        }
                        else{           //重复保存的else
                            Toast.makeText(getApplicationContext(), "BMI为："+putbmi, Toast.LENGTH_SHORT)
                                    .show();//阴影提示框
                        }
                    }else           //超出区间范围（10-300）的else
                    {
                        AlertDialog dlg = new AlertDialog.Builder(View3.this)
//                            .setIcon(R.drawable.icon)     //加入提示框图标
                                .setTitle("提示")
                                .setMessage("请正确输入")
                                .setPositiveButton("确定", null)

                                .create();
                        dlg.show();
                        Log.d("TAG", "Data error");

                    }
                }
                else            //输入为空的else
                {
                    AlertDialog dlg = new AlertDialog.Builder(View3.this)
//                            .setIcon(R.drawable.icon)     //加入提示框图标
                            .setTitle("提示")
                            .setMessage("请输入身高和体重！")
                            .setPositiveButton("确定", null)
                            .create();
                    dlg.show();

                }

            }
        });
    }
}
